const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads');
const bannerDir = path.join(uploadDir, 'banners');

if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

if (!fs.existsSync(bannerDir)) {
  fs.mkdirSync(bannerDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadType = req.params.type || 'general';
    let destDir = uploadDir;

    switch (uploadType) {
      case 'banner':
        destDir = bannerDir;
        break;
      case 'product':
        destDir = path.join(uploadDir, 'products');
        break;
      case 'shop':
        destDir = path.join(uploadDir, 'shops');
        break;
      default:
        destDir = uploadDir;
    }

    // 确保目录存在
    if (!fs.existsSync(destDir)) {
      fs.mkdirSync(destDir, { recursive: true });
    }

    cb(null, destDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const ext = path.extname(file.originalname);
    const filename = `${uuidv4()}${ext}`;
    cb(null, filename);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 检查文件类型
  const allowedTypes = /jpeg|jpg|png|gif|webp/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件 (jpeg, jpg, png, gif, webp)'));
  }
};

// 配置multer
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB限制
  },
  fileFilter: fileFilter
});

/**
 * 上传单个文件
 * POST /api/upload/:type
 */
exports.uploadSingle = (req, res, next) => {
  const uploadSingle = upload.single('file');

  uploadSingle(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(400).json({
          success: false,
          message: '文件大小不能超过5MB'
        });
      }
      return res.status(400).json({
        success: false,
        message: '文件上传错误: ' + err.message
      });
    } else if (err) {
      return res.status(400).json({
        success: false,
        message: err.message
      });
    }

    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的文件'
      });
    }

    // 构建文件URL
    const baseUrl = `${req.protocol}://${req.get('host')}`;
    const uploadType = req.params.type || 'general';
    let urlPath = '';

    switch (uploadType) {
      case 'banner':
        urlPath = '/uploads/banners';
        break;
      case 'product':
        urlPath = '/uploads/products';
        break;
      case 'shop':
        urlPath = '/uploads/shops';
        break;
      default:
        urlPath = '/uploads';
    }

    const fileUrl = `${baseUrl}${urlPath}/${req.file.filename}`;

    res.json({
      success: true,
      message: '文件上传成功',
      data: {
        filename: req.file.filename,
        originalname: req.file.originalname,
        size: req.file.size,
        url: fileUrl,
        path: req.file.path
      }
    });
  });
};

/**
 * 上传多个文件
 * POST /api/upload/:type/multiple
 */
exports.uploadMultiple = (req, res, next) => {
  const uploadMultiple = upload.array('files', 10); // 最多10个文件

  uploadMultiple(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(400).json({
          success: false,
          message: '文件大小不能超过5MB'
        });
      }
      return res.status(400).json({
        success: false,
        message: '文件上传错误: ' + err.message
      });
    } else if (err) {
      return res.status(400).json({
        success: false,
        message: err.message
      });
    }

    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的文件'
      });
    }

    // 构建文件URL列表
    const baseUrl = `${req.protocol}://${req.get('host')}`;
    const files = req.files.map(file => ({
      filename: file.filename,
      originalname: file.originalname,
      size: file.size,
      url: `${baseUrl}/uploads/${req.params.type || 'general'}/${file.filename}`,
      path: file.path
    }));

    res.json({
      success: true,
      message: `成功上传 ${files.length} 个文件`,
      data: files
    });
  });
};

/**
 * 删除文件
 * DELETE /api/upload/:type/:filename
 */
exports.deleteFile = async (req, res, next) => {
  try {
    const { type, filename } = req.params;

    if (!filename) {
      return res.status(400).json({
        success: false,
        message: '文件名不能为空'
      });
    }

    // 构建文件路径
    let filePath;
    switch (type) {
      case 'banner':
        filePath = path.join(bannerDir, filename);
        break;
      case 'product':
        filePath = path.join(uploadDir, 'products', filename);
        break;
      case 'shop':
        filePath = path.join(uploadDir, 'shops', filename);
        break;
      default:
        filePath = path.join(uploadDir, filename);
    }

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }

    // 删除文件
    fs.unlinkSync(filePath);

    res.json({
      success: true,
      message: '文件删除成功'
    });
  } catch (error) {
    console.error('删除文件失败:', error);
    res.status(500).json({
      success: false,
      message: '删除文件失败'
    });
  }
};

/**
 * 获取文件信息
 * GET /api/upload/:type/:filename/info
 */
exports.getFileInfo = async (req, res, next) => {
  try {
    const { type, filename } = req.params;

    if (!filename) {
      return res.status(400).json({
        success: false,
        message: '文件名不能为空'
      });
    }

    // 构建文件路径
    let filePath;
    switch (type) {
      case 'banner':
        filePath = path.join(bannerDir, filename);
        break;
      case 'product':
        filePath = path.join(uploadDir, 'products', filename);
        break;
      case 'shop':
        filePath = path.join(uploadDir, 'shops', filename);
        break;
      default:
        filePath = path.join(uploadDir, filename);
    }

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }

    // 获取文件信息
    const stats = fs.statSync(filePath);
    const baseUrl = `${req.protocol}://${req.get('host')}`;
    const fileUrl = `${baseUrl}/uploads/${type}/${filename}`;

    res.json({
      success: true,
      data: {
        filename: filename,
        size: stats.size,
        url: fileUrl,
        path: filePath,
        createdAt: stats.birthtime,
        modifiedAt: stats.mtime
      }
    });
  } catch (error) {
    console.error('获取文件信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取文件信息失败'
    });
  }
};
